var cheerio = require('cheerio');
var fs = require('fs');
var mysql = require('mysql');
var superagent = require('superagent');

var msyqlConfig = require('./config').config.mysqlOptions;

var question;
var time0;
var time1;
var time2;
var time3;

fn1();

function fn1() {
    time0 = (new Date).getTime();
    let query1 = 'select * from question where flag=0 limit 1 offset 0';
    let connection1 = mysql.createConnection(msyqlConfig);
    connection1.connect();
    connection1.query(query1, function (err, res) {
        if (err) {
            console.log('query1 error');

        } else {
            time1 = (new Date).getTime();
            console.log('time1: ' + (time1 - time0));
            console.log();

            if (res.length > 0) {
                question = res[0];
                fn2();
            }
        }
    });
    connection1.end();
}

function fn2() {
    var questionId = question.id;
    var title = question.title;

    let url = `https://www.zhihu.com/question/${questionId}`;

    superagent(url).end(function (err, res) {
        console.log(questionId);
        console.log(title);

        if (err) {
            console.log('请求失败');
            setTimeout(() => {
                fn2();
            }, 30000);
        } else {
            console.log('请求成功');
            time2 = (new Date).getTime();
            console.log('time2: ' + (time2 - time1));
            console.log();

            let text = res.text;
            // console.log(text);
            fs.writeFile('test1.html', text, function () {})

            let $ = cheerio.load(text);
            try {
                let follwer_count = Number($('.QuestionFollowStatus-counts .NumberBoard-itemValue').eq(0).attr().title);
                let answer_count = Number($('.List-headerText').eq(0).text().replace(/.个回答/g, '').replace(/,/g, ''));
                let query2 = `update question set follower_count=${follwer_count}, answer_count=${answer_count},flag=true where id=${questionId}`;

                let connection2 = mysql.createConnection(msyqlConfig);
                connection2.connect();
                connection2.query(query2, function (err, res) {
                    if (err) {
                        console.log('query2 error');
                        console.log();
                        fn2();
                    } else {
                        console.log('query2 success');
                        console.log(res);
                        time3 = (new Date).getTime();
                        console.log('time3: ' + (time3 - time2));
                        console.log();
                        fn1();
                    }
                });
                connection2.end();
            } catch (error) {
                console.log(error);
                
                setTimeout(() => {
                    fn2();
                }, 30000);
            }

        }
    })
}